package com.bh.weapp.controller.sysuser.shipment;

import com.bh.common.annotation.Log;
import com.bh.common.enums.ShipmentStatus;
import com.bh.common.constant.Symbol;
import com.bh.common.core.controller.BaseController;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.core.domain.entity.SysUser;
import com.bh.common.core.page.TableDataInfo;
import com.bh.common.enums.BusinessType;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.StringUtils;
import com.bh.extend.service.IJcOrderBarcodeService;
import com.bh.framework.web.service.PermissionService;
import com.bh.shipment.domain.JcShipment;
import com.bh.shipment.domain.JcShipmentImg;
import com.bh.shipment.service.IJcShipmentCarryService;
import com.bh.shipment.service.IJcShipmentImgService;
import com.bh.shipment.service.IJcShipmentService;
import com.bh.shipment.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 运单管理Controller
 *
 * @author slx
 * @date 2023-04-22
 */
@Api(tags = {"SYS运单管理"})
@RestController
@RequestMapping("/api/sysuser/shipment")
public class JcShipmentSysApiController extends BaseController {

    @Autowired
    private IJcShipmentService jcShipmentService;
    @Autowired
    private IJcShipmentCarryService jcShipmentCarryService;
    @Autowired
    private IJcShipmentImgService jcShipmentImgService;
    @Autowired
    private IJcOrderBarcodeService jcOrderBarcodeService;
    @Autowired
    private PermissionService permissionService;


    /**
     * 查询运单管理列表， 加一种司机的权限，因为司机的可能参与运单的扫码
     */
    @ApiOperation("查询发运人运单管理列表")
    @PreAuthorize("@ss.hasPermi('api:shipment:from:list')")
    @PostMapping("/fromOrgList")
    public TableDataInfo fromOrgList(@RequestBody JcShipmentSysVo jcShipment) {
        if (!SysUser.isAdmin(getUserId()) && StringUtils.isNotBlank(getOrgIds())) {
            // 获取用户的所有权限,加一种司机的权限，因为司机的可能参与运单
            jcShipment.setJcFromOrganizationIds(getOrgIds());
            if (jcShipment.getStatus() == null) {
                jcShipment.setStatus(ShipmentStatus.ACTIVE.getValue());
            }
            // 查询角色是否是 装卸货司机
            if (permissionService.hasRole("all-driver")) {
                jcShipment.setJcDriverId(getUserId());
            }
            // 必须是组织装货人员才能查询接口
            startPage();
            List<JcShipmentSysApiVO> list = jcShipmentService.selectJcShipmentSysList(jcShipment);
            return getDataTable(list);
        }
        return getDataTable(null);
    }


    /**
     * 查询司机运单管理列表
     */
    @ApiOperation("查询司机运单管理列表")
    @PreAuthorize("@ss.hasPermi('api:shipment:driver:list')")
    @PostMapping("/driverList")
    public TableDataInfo driverList(@RequestBody JcShipmentSysVo jcShipment) {
        if (jcShipment.getStatus() < 2) {
            throw new ServiceException("运单状态不正确");
        }
        if (!SysUser.isAdmin(getUserId())) {
            jcShipment.setJcDriverId(getUserId());
        }
        if (jcShipment.getStatus() != null && jcShipment.getStatus() == 2) {
            // 需要加一种 已配载 的状态，主要原因是因为目前已配载没有具体使用
            jcShipment.setStatus(null);
            jcShipment.setStatusStr("2,3");
        }
        if (jcShipment.getStatus() != null && jcShipment.getStatus() == 4) {
            // 需要加一种  VEHICLE_ARRIVE 4，6,司机不需要 5
            jcShipment.setStatusStr("4,6");
            jcShipment.setStatus(null);
        }
        startPage();
        List<JcShipmentSysApiVO> list = jcShipmentService.selectDriverJcShipmentList(jcShipment);
        return getDataTable(list);
    }

    /**
     * 网点经理管理人员可以进行查看运单并进行确认
     *
     * @param jcShipment
     * @return
     */
    @ApiOperation("查询网点运单管理列表")
    @PreAuthorize("@ss.hasPermi('api:shipment:to:list')")
    @PostMapping("/toOrgList")
    public TableDataInfo toOrgList(@RequestBody JcShipmentSysVo jcShipment) {
        if (!SysUser.isAdmin(getUserId()) && StringUtils.isNotBlank(getOrgIds())) {
            // 获取用户的所有权限
            jcShipment.setOrgIds(getOrgIds());
            if (jcShipment.getStatus() == 4) {
                // 需要加一种  VEHICLE_ARRIVE 4,5,6
                jcShipment.setStatusStr("4,5,6");
                jcShipment.setStatus(null);
            }
            // 查询角色是否是 装卸货司机
            if (permissionService.hasRole("all-driver")) {
                jcShipment.setJcDriverId(getUserId());
            }
            // 必须是组织接货人员才能查询接口
            startPage();
            List<JcShipmentSysApiVO> list = jcShipmentService.selectJcShipmentSysList(jcShipment);
            return getDataTable(list);
        }
        return getDataTable(null);

    }

    /**
     * 运单管理, 可以传 code、id
     */
    @ApiOperation("扫码查询运单")
    @PreAuthorize("@ss.hasPermi('api:shipment:info')")
    @GetMapping("/getInfoByCode/{code}")
    public AjaxResult getInfoByCode(@PathVariable("code") String code) {
        JcShipmentUnloadVo jcShipment = jcShipmentService.selectJcShipmentUnloadVoByCode(code);
        if (jcShipment == null) {
            return error("运单不存在");
        }
        return AjaxResult.success(jcShipment);
    }

    /**
     * 新增保存运单管理--未知
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("新增或修改保存运单")
    @PreAuthorize("@ss.hasPermi('api:shipment:add')")
    @Log(title = "运单管理", businessType = BusinessType.INSERT)
    @PostMapping("/saveShipment")
    public AjaxResult saveShipment(@RequestBody JcShipment jcShipment) {
        if (jcShipment.getTime() == null) {
            return error("运单时间不能为空");
        }
        if (jcShipment.getJcVehicleId() == null) {
            return error("车型不能为空");
        }

        Integer status = jcShipment.getStatus();
        if (status != null && (status > 1 || status < 0)) {
            return error("运单不能保存，请联系管理员");
        }
        return toAjax(jcShipmentService.insertOrUpdateJcShipment(jcShipment));
    }


    /**
     * 新增保存运单装车图片-拣货员
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('api:shipment:img:add')")
    @ApiOperation("新增保存运单装车图片")
    @Log(title = "运单装车图片", businessType = BusinessType.INSERT)
    @PostMapping("/addImg")
    public AjaxResult addImgSave(@RequestBody @Validated JcShipmentImgVo shipmentImgVo) {
        boolean success = false;
        if (StringUtils.isNotEmpty(shipmentImgVo.getImgUrls())) {
            List<JcShipmentImg> imgs = new ArrayList<>();
            String[] voImgUrls = shipmentImgVo.getImgUrls().split(Symbol.COMMA);
            for (String imgUrl : voImgUrls) {
                JcShipmentImg jcShipmentImg = new JcShipmentImg();
                jcShipmentImg.setJcShipmentId(shipmentImgVo.getJcShipmentId());
                jcShipmentImg.setImgUrl(imgUrl);
                imgs.add(jcShipmentImg);
            }
            success = jcShipmentImgService.saveBatch(imgs);
        }
        return toAjax(success);
    }

    /**
     * 运单配载分段订单-拣货员
     *
     * @param shipmentVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('api:shipment:confirm')")
    @ApiOperation("确认所有货品装车")
    @PostMapping("/addLed")
    public AjaxResult addLed(@RequestBody JcAddShipmentVo shipmentVo) {
        return toAjax(jcShipmentCarryService.addLed(shipmentVo));
    }


    /**
     * 发运-司机
     *
     * @param shipmentId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('api:shipment:updateReg')")
    @ApiOperation("确认发运")
    @PostMapping("/updateRegTime/{shipmentId}")
    public AjaxResult updateRegTime(@PathVariable("shipmentId") Long shipmentId) {
        JcShipment shipment = jcShipmentService.getById(shipmentId);
        List<String> noUnloadLedIds = jcOrderBarcodeService.selectNoUnloadLedIdsByShipmentIdAndOrgId(shipmentId, shipment.getJcNowOrganizationId());
        if (noUnloadLedIds != null && noUnloadLedIds.size() > 0) {
            return error("该站点还有分段订单商品未卸货, 请先完成卸货");
        }
        return toAjax(jcShipmentService.updateRegTime(shipmentId, "driver"));
    }

    /**
     * 确认运抵-司机
     *
     * @param shipmentId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('api:shipment:arrived')")
    @ApiOperation("确认运抵")
    @PostMapping("/updateArrivedTime/{shipmentId}")
    public AjaxResult updateArrivedTime(@PathVariable("shipmentId") Long shipmentId) {
        // 首先确认到达那个区域
        return toAjax(jcShipmentService.updateArrivedTime(shipmentId, new Date()));
    }

    /**
     * 确认运输完毕-已经不使用
     *
     * @param addShipmentFinishedVo
     * @return
     */
    @Deprecated
    @PreAuthorize("@ss.hasPermi('api:shipment:finished')")
    @ApiOperation("确认运输完毕")
    @PostMapping("/updateTransportFinished")
    public AjaxResult updateTransportFinished(@RequestBody JcShipmentFinishedVo addShipmentFinishedVo) {
        return toAjax(jcShipmentService.updateTransportFinished(addShipmentFinishedVo));
    }


    /**
     * 确认所属货品卸车-网点管理员
     *
     * @param shipmentId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('api:shipment:unload:finished')")
    @ApiOperation("确认所属货品卸车")
    @PostMapping("/unloadFinished/{shipmentId}")
    public AjaxResult unloadFinished(@PathVariable Long shipmentId) {
        int num = jcShipmentService.unloadFinished(shipmentId);
        if (num > 1) {
            return AjaxResult.success("卸车成功");
        } else if (num == 1) {
            return AjaxResult.success("部分卸车成功");
        } else {
            return AjaxResult.error("卸车失败,请检查订单中是否有未卸货的订单");
        }
    }
}
